import { ChapterContext } from '@/hooks/useChapterContext'
import BaseNode from '@/Model/Node/BaseNode'
import DecisionNode from '@/Model/Node/DecisionNode'
import React, { useContext, useEffect, useLayoutEffect, useState } from 'react'
import CommonCard from './CommonCard'
import DecisionCard from './DecisionCard'
import StartCard from './StartCard'

export default function NodeEditor(){
  const chapterContext = useContext(ChapterContext)
  const [chapter, setChapter] = chapterContext?.chapter
  const [currentCard, setCurrentCard] = chapterContext.currentCard
  const [refresh, _] = chapterContext.refresh
  const nodes = chapter.nodes
  const keys = Object.keys(chapter.nodes)

  const [showKeys, setShowKeys] = useState<string[]>([])

  const findShowList = ()=>{
    const tempKeys = nodes?.[currentCard] ? [currentCard] :[]
    const findPrev =(node:BaseNode)=>{
      if(node?.prev && node.type!=='decision'){
        tempKeys.unshift(node.prev)
        findPrev(nodes[node.prev])
      }
    }
    const findNext = (node:BaseNode)=>{
      if(node?.next){
        tempKeys.push(node.next)
        findNext(nodes[node.next])
      }
    }
    findPrev(nodes[currentCard])
    findNext(nodes[currentCard])
    return tempKeys
  }

  useEffect(()=>{
    setShowKeys(findShowList())
  },[currentCard, refresh])
  
  return <div style={{padding: '20px', minHeight: '100%', background: '#f3f3f3', paddingLeft:'30%', paddingBottom:500}}>
    {showKeys.map((item:string, index:number) => {
      if (chapter.nodes[item]?.type === 'start') {
        return <StartCard key={chapter.nodes[item].uuid} data={chapter.nodes[item]} />
      }
      if (chapter.nodes[item]?.type === 'common') {
        return <CommonCard key={chapter.nodes[item].uuid} data={chapter.nodes[item]} />
      }
      if (chapter.nodes[item]?.type === 'decision') {
        return <DecisionCard key={chapter.nodes[item].uuid} data={chapter.nodes[item] as DecisionNode} />
      }
    })}
  </div>
}

